/*
 * 등록버튼 누를때 유효성 검사해주는 코드와
 * 등록을 ajax를 이용하여 구현
 */
function check(name, tabs){	
	$.extend($.validator.messages, {
		required:"필수 입력",
		number:"숫자만 입력하세요."
	});
	if(name=="pInForm"){
		$("#pInForm").validate({
			rules:{
				pName:{required:true},
				pEa:{required:true,
					number:true},
				pPrice:{required:true,
					number:true},
			},
			submitHandler: function(form){
				insert(name,tabs);
			},
			errorPlacement: function(error, element){
				error.insertAfter(element);
			}
		});
	}else{
		$("#cInForm").validate({
			groups: {
				phone:"cPhone1 cPhone2 cPhone3",
				reg:"cRegNum1 cRegNum2 cRegNum3"
			},
			rules:{
				cName:{required:true},
				cPhone1:{required:true
					,number:true},
				cPhone2:{required:true
					,number:true},
				cPhone3:{required:true,
					number:true},
				cRegNum1:{required:true, 
					minlength: 3, 
					maxlength:3,
					number:true},
				cRegNum2:{required:true, 
					minlength: 2, 
					maxlength:2,
					number:true},
				cRegNum3:{required:true, 
					minlength: 5, 
					maxlength:5,
					number:true},
				cLoc:{required:true},
				cCeo:{required:true}
			},
			messages:{
				cRegNum1:{ 
					minlength: "사업자번호는 3자리-2자리-5자리입니다.",
					maxlength: "사업자번호는 3자리-2자리-5자리입니다."},
				cRegNum2:{
					minlength: "사업자번호는 3자리-2자리-5자리입니다.",
					maxlength: "사업자번호는 3자리-2자리-5자리입니다."},
				cRegNum3:{ 
					minlength: "사업자번호는 3자리-2자리-5자리입니다.",
					maxlength: "사업자번호는 3자리-2자리-5자리입니다."}
			},
			submitHandler: function(form){
				insert(name,tabs);
			},
			errorPlacement: function(error, element){
				if(element.attr("name")=="cPhone1"||element.attr("name")=="cPhone2"||element.attr("name")=="cPhone3"){
					error.insertAfter("#cPhone3");
				} else if(element.attr("name")=="cRegNum1"||element.attr("name")=="cRegNum2"||element.attr("name")=="cRegNum3"){
					error.insertAfter("#cRegNum3");
				} else {
					error.insertAfter(element);
				}
			}
		});
	}
}

function insert(name,tabs){
	if(name=="pInsert"){
		$.ajax({
			url : '/templateType/type4/insProduct.do',
			data : $("#pInForm").serialize(),
			type : "post",
			dataType : "html",
			success : function(data) {
				alert(data);
			},
			error : function(jqXHR, textStatus, errorThrown) {
				alert( errorThrown );
				alert( jqXHR.status );
			}
		});
	}else {
		$.ajax({
			url : '/templateType/type4/insCorp.do',
			type : "post",
			data : $("#cInForm").serialize(),
			dataType : "html",
			success : function(data) {
				alert(data);
				location.replace("/templateType/typeFour.do");
			},
			error : function(jqXHR, textStatus, errorThrown) {
				alert( errorThrown );
				alert( jqXHR.status );
			}
		});
	}		
}
